'''
1 多路径图
2 

'''

import pandas as pd
import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
import matplotlib.dates as mdates
import cartopy.crs as ccrs
from cartopy.mpl.ticker import LongitudeFormatter,LatitudeFormatter
import cartopy.feature as cfeature
import shapely.geometry as sgeom
from datetime import datetime


# mean
meanpath = r"C:\Users\12475\Desktop\typhoon\2025.2.5\trmatch_cntl_tr0016_mean" 

# reanalysis
n0path= r"C:\Users\12475\Desktop\typhoon\2025.2.5\TRACK_ID_0"

# other path
directory =  'C:\\Users\\12475\\Desktop\\typhoon\\2025.2.5\\'    # 要筛选的文件开头
start = 'TRACK_ID'   # 获取目录下所有文件和子目录
all_files = os.listdir(directory)   # 过滤出文件且符合后缀要求
filtered_files = [f for f in all_files if f.startswith(start) and f != "TRACK_ID_0"]   # 打印所有符合后缀的文件名


class tydat:
    def __init__(self,path,skiprows=2,extent=[100,170,10,60]):  # default - dusurui
        self.df=pd.read_csv(path,skiprows=skiprows,engine='python',sep=' & |\s',header=None) 
        self.colors=['#000000','#00ffff','#0000ff', '#FF8C00','#FF0000','#FF00FF']
        lon= self.df[8].values
        lat=self.df[9].values
        self.lon,self.lat=self.cntrl_lonlat(lon,lat)
        self.tp = self.df[14]
        self.umax = self.df[13]
        self.pmin = self.df[10]
        self.extent=extent
        # 这里需要转成datetime对象
        self.time = [datetime.strptime(str(t),'%Y%m%d%H') for t in self.df[0] ]
        
    def cntrl_lonlat(self,lon,lat):
        lon = lon[(lon>=0) & (lon <=360)] #去异常   有e25次方
        lat = lat[(lat>=-90) & (lat <=90)]  # 去异常
        lon=np.where(lon>180,180,lon)  #防止左右边界相连
        return lon,lat

def basemap(ax,ty,title=None):
    ax.add_feature(cfeature.COASTLINE) #海岸线
    ax.add_feature(cfeature.BORDERS, linestyle=':')   #国界
    china_provinces = cfeature.NaturalEarthFeature(category='cultural',name='admin_1_states_provinces_lines', scale='10m', facecolor='none')
    ax.add_feature(china_provinces, edgecolor='black', linewidth=0.5) #省界
    ax.set(xlim=(ty.extent[0],ty.extent[1]))
    ax.set(ylim=(ty.extent[2],ty.extent[3]))    
    #这种设定方法适用于这样子给出范围。
    ax.set_xticks(np.linspace(ty.extent[0], ty.extent[1]+5, 5))
    ax.set_yticks(np.linspace(ty.extent[2], ty.extent[3]+5, 5))
    ax.xaxis.set_major_formatter(LongitudeFormatter(number_format='.1f'))
    ax.xaxis.set_minor_locator(plt.MultipleLocator(1))
    ax.yaxis.set_major_formatter(LatitudeFormatter(number_format='.1f'))
    ax.yaxis.set_minor_locator(plt.MultipleLocator(1))
    ax.tick_params(axis='both', labelsize=6, direction='out')
    # ax.set_title(title)

def track(ax,ty,sep=1,color='Black'):
    lon= ty.lon
    lat= ty.lat
    ll2=np.arange(0,len(lon)-1,1)
    # 连线
    for i in ll2:
        pointA = lon[i],lat[i]
        pointB = lon[i+1],lat[i+1]
        ax.add_geometries([sgeom.LineString([pointA, pointB])], color=color,crs=ccrs.PlateCarree())      


fig,ax= plt.subplots(subplot_kw={'projection': ccrs.PlateCarree()},dpi=300,figsize=(10,5))


#绘制track 图
path=r'C:\Users\12475\Desktop\typhoon\2025.2.5'
for f in filtered_files:
    ty=tydat(path+"\\"+f)
    track(ax,ty,color="Black")
# 绘制mean
ty=tydat(meanpath,skiprows=5)  
basemap(ax,ty,title="abc")  
track(ax,ty,color="lime")
# 绘制trackid 0
ty=tydat(n0path,skiprows=2)  
track(ax,ty,color="Red")
ax.set_title()



